package com.it.config;

import cn.hutool.json.JSONUtil;
import com.it.utisl.JwtUtils;
import com.it.vo.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * TODO
 *
 * @author: Coke
 * @DateTime: 2023/11/19/22:14
 **/
@Component
public class JwtLogoutSuccessHandler implements LogoutSuccessHandler {
    @Autowired
    private JwtUtils jwtUtils;
    
    @Override
    // 处理注销成功的逻辑
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
          throws IOException, ServletException {
        // 如果认证信息不为空，则使用 SecurityContextLogoutHandler 进行注销
        if (authentication != null) {
            new SecurityContextLogoutHandler().logout(request, response, authentication);
        }
        
        // 设置响应的内容类型为JSON，使用UTF-8字符集
        response.setContentType("application/json;charset=UTF-8");
        
        // 将JWT的头部设置为空字符串，即清除JWT
        response.setHeader(jwtUtils.getHeader(), "");
        
        // 获取响应输出流
        ServletOutputStream out = response.getOutputStream();
        
        // 构建成功响应
        Response<?> ok = Response.ok();
        
        // 将成功响应转换为JSON字符串，并写入输出流中
        out.write(JSONUtil.toJsonStr(ok).getBytes(StandardCharsets.UTF_8));
        
        // 刷新输出流
        out.flush();
        
        // 关闭输出流
        out.close();
    }
}
